package fileSearchSystem;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import automaticTagging.AutomaticTagging;

import com.cloudgarden.resource.SWTResourceManager;

import dbManager.Manager;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class GUI extends org.eclipse.swt.widgets.Composite implements Observer 
{
	//Components of the GUI
	private Button searchButton;
	private Button empty_table;
	private Text solution_from_hql;
	private Combo options_combo_box;
	private Button clear_query;
	private Table tags_table;
	private Label query_label;
	private SearchExecuter se;
	private truncExecuter te;
	private updateExecuter ue;
	private Manager manager;
	int paranthesis_counter = 0;
	private Combo option_combo_box2;

	{
		//Register as a resource user - SWTResourceManager will
		//handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	/**
	 * this function is the GUI class constructor
	 * @param parent - the GUI composite
	 * @param style - the GUI style
	 */
	public GUI(Composite parent, int style)
	{
		super(parent, style);
		se = SearchExecuter.getInstance();
		te = truncExecuter.getInstance();
		ue = updateExecuter.getInstance();
		manager = Manager.getInstance();
		//the GUI is observer.every change in DB we inform the GUI
		manager.addObserver(this);
		initGUI();
	}
	
	/**
	* Initializes the GUI.
	*/
	private void initGUI() 
	{
		try 
		{
			this.setSize(679, 430);
			this.setBackground(SWTResourceManager.getColor(0, 128, 64));
			FormLayout thisLayout = new FormLayout();
			this.setLayout(thisLayout);
			
			// Jigloo automatic creation of option_combo_box2
			{
				option_combo_box2 = new Combo(this, SWT.NONE);
				FormData option_combo_box2LData = new FormData();
				option_combo_box2LData.left =  new FormAttachment(0, 1000, 8);
				option_combo_box2LData.top =  new FormAttachment(0, 1000, 20);
				option_combo_box2LData.width = 130;
				option_combo_box2LData.height = 22;
				option_combo_box2.setLayoutData(option_combo_box2LData);
				String items[] = { "(", "~", ")"};
				option_combo_box2.setItems(items);
				option_combo_box2.setText("choose logical operator");
				option_combo_box2.setBackground(SWTResourceManager.getColor(240, 240, 240));
				option_combo_box2.addSelectionListener(new SelectionListener() 
				{
					/**
					 * check the logical operator the user chose
					 */
					@Override
					public void widgetSelected(SelectionEvent e) 
					{
						int index = option_combo_box2.getSelectionIndex();
						if (index == -1)
							return;
						//check the logical operator the user chose
						String option = option_combo_box2.getItem(index);
						option_combo_box2.clearSelection();
						option_combo_box2.setEnabled(true);
						searchButton.setEnabled(true);
						tags_table.setEnabled(true);
						//append to query_label the logical operator that was chosen
						query_label.setText(query_label.getText()+option);
						//check if the chosen logical operator is '('
						if (index == 0)
						{
							paranthesis_counter++;
						}
						//check if the chosen logical operator is ')'
						if (index == 2)
						{
							paranthesis_counter--;
						}
						//the case there is illegal number of parenthesis
						if (paranthesis_counter < 0)
						{
							//in this case we need to isert a new query
							
							paranthesis_counter = 0;
							MessageBox message_box = new MessageBox(getShell(),SWT.ERROR);
							message_box.setMessage("paranthesis problem");
							message_box.open();
							query_label.setText("");
							tags_table.setEnabled(true);
							searchButton.setEnabled(false);
							option_combo_box2.setEnabled(true);
						}
						String items[] = { "(", "~", ")"};
						option_combo_box2.setItems(items);
						option_combo_box2.setText("choose logical operator");
					}
					@Override
					public void widgetDefaultSelected(SelectionEvent arg0) {}
				});	


			}
			// Jigloo automatic creation of option_combo_box
			{
				options_combo_box = new Combo(this, SWT.NONE);
				FormData options_combo_boxLData = new FormData();
				options_combo_boxLData.left =  new FormAttachment(0, 1000, 188);
				options_combo_boxLData.top =  new FormAttachment(0, 1000, 20);
				options_combo_boxLData.width = 170;
				options_combo_boxLData.height = 22;
				options_combo_box.setLayoutData(options_combo_boxLData);
				options_combo_box.setBackground(SWTResourceManager.getColor(240, 240, 240));
				options_combo_box.setEnabled(false);
				String items[] = {"&&", "||" };
				options_combo_box.setItems(items);
				options_combo_box.setText("choose binary logical operator");
				options_combo_box.addSelectionListener(new SelectionListener() 
				{
					/**
					 * check the binary logical operator the user chose
					 */
					@Override
					public void widgetSelected(SelectionEvent e) 
					{
						int index = options_combo_box.getSelectionIndex();
						if (index == -1)
							return;
						//the operator the user chose
						String option = options_combo_box.getItem(index);
						options_combo_box.clearSelection();
						options_combo_box.setText("choose binary logical operator");
						options_combo_box.setEnabled(false);
						searchButton.setEnabled(false);
						tags_table.setEnabled(true);
						//append to query_label the binary logical operator that was chosen
						query_label.setText(query_label.getText()+option);
						 
						/*we want to ensure legal query, therefore after binary logical operator 
						 * can be just '(' in the items of option_combo_box2*/
						String items[] = { "("};
						option_combo_box2.setItems(items);
						option_combo_box2.setText("choose logical operator");
					}
					@Override
					public void widgetDefaultSelected(SelectionEvent arg0) {}
				});	
			}
			// Jigloo automatic creation of button clear_query
			{
				clear_query = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData clear_queryLData = new FormData();
				clear_queryLData.left =  new FormAttachment(0, 1000, 391);
				clear_queryLData.top =  new FormAttachment(0, 1000, 20);
				clear_queryLData.width = 86;
				clear_queryLData.height = 24;
				clear_query.setLayoutData(clear_queryLData);
				clear_query.setText("clear query");
				clear_query.addMouseListener(new MouseListener()
				{
					@Override
					public void mouseUp(MouseEvent arg0)
					{
						/*the user want to insert another query therefore we initialize the components*/
						query_label.setText("");
						tags_table.setEnabled(true);
						searchButton.setEnabled(false);
						options_combo_box.setEnabled(false);
						String items[] = { "(", "~", ")"};
						option_combo_box2.setItems(items);
						option_combo_box2.setText("choose logical operator");
						paranthesis_counter = 0;
					}
					
					@Override
					public void mouseDown(MouseEvent arg0) {}
					
					@Override
					public void mouseDoubleClick(MouseEvent arg0) {}
				});
			}
			// Jigloo automatic creation of tags_table
			{
				FormData tags_tableLData = new FormData();
				tags_tableLData.left =  new FormAttachment(0, 1000, 33);
				tags_tableLData.top =  new FormAttachment(0, 1000, 96);
				tags_tableLData.width = 281;
				tags_tableLData.height = 295;
				tags_table = new Table(this, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
				tags_table.setLayoutData(tags_tableLData);
				updateTablel();
				
				// the listener for clicking an element of the table (double click)
				tags_table.addSelectionListener(new SelectionListener() 
				{
					
					@Override
					public void widgetSelected(SelectionEvent arg0) {}
					
					@Override
					public void widgetDefaultSelected(SelectionEvent arg0)
					{
						TableItem item = (TableItem) arg0.item;
						String text = item.getText();
						tags_table.setEnabled(false);
						//we append the selected tag to the query
						query_label.setText(query_label.getText() + text);
						searchButton.setEnabled(true);
						options_combo_box.setEnabled(true);
						String items[] = { "(", "~", ")"};
						option_combo_box2.setItems(items);
						option_combo_box2.setText("choose logical operator");
						solution_from_hql.setText("");
					}
				});
			}
			// Jigloo automatic creation of query_label
			{
				FormData query_labelLData = new FormData();
				query_labelLData.left =  new FormAttachment(0, 1000, 12);
				query_labelLData.top =  new FormAttachment(0, 1000, 55);
				query_labelLData.width = 647;
				query_labelLData.height = 21;
				query_label = new Label(this, SWT.NONE);
				query_label.setLayoutData(query_labelLData);
			}
			// Jigloo automatic creation of solution_from_hql
			{
				FormData solution_from_hqlLData = new FormData();
				solution_from_hqlLData.left =  new FormAttachment(0, 1000, 372);
				solution_from_hqlLData.top =  new FormAttachment(0, 1000, 96);
				solution_from_hqlLData.width = 271;
				solution_from_hqlLData.height = 295;
				solution_from_hql = new Text(this, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
				solution_from_hql.setLayoutData(solution_from_hqlLData);
			}
			// Jigloo automatic creation of button empty_table
			{
				empty_table = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData empty_tableLData = new FormData();
				empty_tableLData.left =  new FormAttachment(0, 1000, 483);
				empty_tableLData.top =  new FormAttachment(0, 1000, 20);
				empty_tableLData.width = 95;
				empty_tableLData.height = 24;
				empty_table.setLayoutData(empty_tableLData);
				empty_table.setText("truncate table");
				empty_table.setBackground(SWTResourceManager.getColor(255, 0, 128));
				empty_table.addMouseListener(new MouseListener()
				{
					public void mouseUp(MouseEvent e) 
					{
						//truncate the table 'tags'
						te.execute();
						query_label.setText("");
						tags_table.setEnabled(true);
						searchButton.setEnabled(false);
						tags_table.removeAll();
						String items[] = { "(", "~", ")"};
						option_combo_box2.setItems(items);
						option_combo_box2.setText("choose logical operator");
						option_combo_box2.setEnabled(true);
						options_combo_box.setEnabled(false);
						solution_from_hql.setText("");
						paranthesis_counter = 0;
					}
					public void mouseDown(MouseEvent arg0) {}
					public void mouseDoubleClick(MouseEvent arg0) {}
				});
			}
			// Jigloo automatic creation of button searchButton
			{
				searchButton = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData searchButtonLData = new FormData();
				searchButtonLData.left =  new FormAttachment(0, 1000, 584);
				searchButtonLData.top =  new FormAttachment(0, 1000, 20);
				searchButtonLData.width = 75;
				searchButtonLData.height = 23;
				searchButton.setLayoutData(searchButtonLData);
				searchButton.setText("search files");
				searchButton.setBackground(SWTResourceManager.getColor(255, 0, 128));
				searchButton.setEnabled(false);
			}
			searchButton.addMouseListener(new MouseListener() 
			{
				public void mouseUp(MouseEvent arg0) 
				{
					//the case there is illegal number of parenthesis
					if (paranthesis_counter != 0)
					{
						MessageBox message_box = new MessageBox(getShell(),SWT.ERROR);
						message_box.setMessage("paranthesis problem");
						message_box.open();
						return; 
					}
					
					solution_from_hql.setText("");
					//update the executer with the query
					se.setSearchString(query_label.getText());
					se.setFile_text(solution_from_hql);
					//process the query and insert file_text the results
					se.execute();
					
					/*initialization for the next query*/
					query_label.setText("");
					searchButton.setEnabled(false);
					tags_table.setEnabled(true);
					String items[] = { "(", "~", ")"};
					option_combo_box2.setItems(items);
					option_combo_box2.setText("choose logical operator");
					options_combo_box.setEnabled(false);
					option_combo_box2.setEnabled(true);
					paranthesis_counter = 0;
				}
				public void mouseDown(MouseEvent arg0) {}
				public void mouseDoubleClick(MouseEvent arg0) {}
			});
			this.layout();
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	/**
	* Auto-generated main method to display this 
	* org.eclipse.swt.widgets.Composite inside a new Shell.
	*/
	public static void main(String[] args) 
	{
		final AutomaticTagging at = new AutomaticTagging();
		Thread t = new Thread(at);
		t.start();
		Display display = Display.getDefault();
		Shell shell = new Shell(display,SWT.MIN);
		shell.addDisposeListener(new DisposeListener() 
		{	
			@Override
			public void widgetDisposed(DisposeEvent arg0) 
			{
				try 
				{
					at.close();
				} 
				catch (IOException e) {}
			}
		});
		GUI inst = new GUI(shell, SWT.NULL);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if(size.x == 0 && size.y == 0) 
		{
			inst.pack();
			shell.pack();
		} 
		else 
		{
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		shell.open();
		while (!shell.isDisposed()) 
		{
			if (!display.readAndDispatch())
				display.sleep();
		}
		//the case the shell was disposed. 
		//we inform automatic tagging about this for closing the sockets in correct way
		at.setMainIsActive(false);
	}
	
	/**
	 * Update the table tags_table with the updated DB tags
	 */
	public void updateTablel()
	{
		tags_table.removeAll();
		ue.setTags(tags_table);
		ue.execute();
	}

	/**
	 * Called when there is change in DB tags.the function update the tags_table accordingly
	 */
	@Override
	public void update(Observable o, Object arg)
	{
		   getDisplay().asyncExec(new Runnable() 
		   {
		        public void run() 
		        {
		        	updateTablel();
		        }
		    });
	}
}
